package com.xiaodou.mjf.web.xface.user.controller;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.service.AccountService;
import com.xiaodou.mjf.application.core.service.FinancialPackageService;
import com.xiaodou.mjf.application.core.service.FinancingAttributeService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.InvestService;
import com.xiaodou.mjf.application.core.service.LoanService;
import com.xiaodou.mjf.application.core.service.NotesBookService;
import com.xiaodou.mjf.application.fee.service.AccountFeeService;
import com.xiaodou.mjf.application.fee.service.LoanMasterService;
import com.xiaodou.mjf.entity.core.Account;
import com.xiaodou.mjf.entity.core.FinancialPackage;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingAttribute;
import com.xiaodou.mjf.entity.core.Invest;
import com.xiaodou.mjf.entity.core.Loan;
import com.xiaodou.mjf.entity.core.NotesBook;
import com.xiaodou.mjf.entity.fee.LoanMaster;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.user.domain.BuyRecord;
import com.xiaodou.mjf.web.xface.user.domain.ProductTradeDetail;
import com.xiaodou.mjf.web.xface.user.domain.TradeRecord;
import com.xiaodou.mjf.web.xface.user.domain.Transaction;
import com.xiaodou.mjf.web.xface.user.domain.beautyFinanceSubscriptionInfo;

@RestController
@RequestMapping("v1/trade_records")
public class TradeRecordController extends ApiController {

	@Resource
	NotesBookService notesBookService;
	@Resource
	AccountService accountService;
	@Resource
	InvestService investService;
	@Resource
	FinancingService financingService;
	@Resource
	FinancingAttributeService financingAttributeService;
	@Resource
	LoanService loanService;
	@Resource
	FinancialPackageService financialPackageService;
	@Resource
	AccountFeeService accountFeeService;
	@Resource
	LoanMasterService loanMasterService; 

	@RequestMapping("my/staging/{oid}")
	Map<String, Object> orderDetail(
			@RequestHeader(required = false) String uid,
			@PathVariable String oid) {
		Map<String,Object> result = success();
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		ProductTradeDetail productTradeDetail = new ProductTradeDetail();
		productTradeDetail.setExchangeStatus("01");
		productTradeDetail.setInvestAmount(100.0D);
		productTradeDetail.setName("小豆一号");
		productTradeDetail.setProfitRate(0.35);
		productTradeDetail.setRepaymentDate(Date.valueOf("2015-02-01"));
		productTradeDetail.setTerm("90");
		productTradeDetail.setValueDate(Date.valueOf("2015-01-01"));

		result.put("name", productTradeDetail.getName());
		result.put("invest_amount", productTradeDetail.getInvestAmount());
		result.put("term", productTradeDetail.getTerm());
		result.put("profit_rate", productTradeDetail.getProfitRate());
		result.put("value_date", productTradeDetail.getValueDate());
		result.put("repayment_date", productTradeDetail.getRepaymentDate());
		result.put("exchange_status", productTradeDetail.getExchangeStatus());

		return result;
	}

	/**
	 * 美丽分期账单列表查询
	 * 
	 * @param uid
	 *            客户编号
	 * @param start
	 *            产品列表起始位置
	 * @param row
	 *            分页显示行数
	 * */
	
	@RequestMapping("my/staging")
	Map<String, Object> staging(@RequestHeader(required = false) String uid, Integer start,
			Integer row) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		if (start == null || start < 0) {
			start = 0;
		}
		if (row == null) {
			row = 20;
		}
		Map<String,Object> result = success();
		Loan loan = new Loan();
		loan.setMemberId(uid);
		loan.setStart(start);
		loan.setLimit(row);
		Page<Loan> page = loanService.page(loan);
		List<Loan> loanList = page.getContent();
		
		List<TradeRecord> records = new ArrayList<TradeRecord>();
		/**
		 * 订单ID oid 产品编号 id 产品名称 name 购买金额 amount 购买日期 purchase_date 交易状态 status
		 * 分期期数 installments 已还期数 repaid_count 机构名称 organization_name 机构电话 organization_phone 
		 * 期数 term 贷款金额 loanAmount 首付金额 downPaymentDeposit 首付比例 downPaymentScale 每期还款 termRepaymenAmount
		 * */
		//每期还款 
		Double termRepaymenAmount = 0D;		
		for (Loan entity : loanList) {
			//edit by David 2015/04/20 start TODO 手续费暂固定为0.02
			termRepaymenAmount= roundDouble((entity.getLoanAmount()/entity.getTerm())*1.02,2);
			//edit by David 2015/04/20 end 
			//交易状态 01为待审核，02为还款中，03为已还清
			//当状态为还款中时，从后台返回总分期数，否则不返回
			//当状态为还款中是，从后台返回已还期数，否则不返回 
			int status=entity.getStatus().intValue();
			int financeStatus = entity.getFinanceStatus()==null?-1:entity.getFinanceStatus().intValue();
			/**
			0	审核通过			1	审核失败
			2	待审核			3	已取消
			4	申请失败			5	放款中
			6	还款中			7	已还清*/
			if(status==1){
				status=3;
			}else if(status==3){
				status=1;
			}
			//若下面状态存在，则覆盖上面状态
			if (financeStatus != -1 && financeStatus!=0) {
				status = entity.getFinanceStatus().intValue();
			}	
			//计算已还期数 add by David 2015/04/20 start 
			LoanMaster loanMaster=(loanMasterService.findByLoanId(entity.getId()));
			int term =0;
			if(loanMaster!=null){
				term = accountFeeService.sumTerm(loanMaster.getAccountNumber(), 0,entity.getMemberId());
			}
			//add by David 2015/04/20 end 
			records.add(new TradeRecord(entity.getId(), entity.getProductId(),entity.getProjectName(), 
					entity.getLoanAmount()+entity.getDownPaymentDeposit(),entity.getCreateTime(),status,entity.getTerm(),term,entity.getOrganizationName(),entity.getOrganizationPhone(),entity.getTerm(),entity.getLoanAmount()+entity.getDownPaymentDeposit(),
					entity.getDownPaymentDeposit(),String.valueOf(entity.getDownPaymentDeposit().doubleValue()*100/(entity.getLoanAmount().doubleValue()+entity.getDownPaymentDeposit().doubleValue())),roundDouble(termRepaymenAmount,2)));
		}
		result.put("items", records);
		return result;
	}

	@RequestMapping("{id}/staging/{oid}")
	Map<String, Object> orderDetail(@PathVariable String id,
			@RequestHeader(required = false) String uid,
			@PathVariable String oid) {
		Map<String,Object> result = success();
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		ProductTradeDetail productTradeDetail = new ProductTradeDetail();
		productTradeDetail.setExchangeStatus("01");
		productTradeDetail.setInvestAmount(100.0D);
		productTradeDetail.setName("小豆一号");
		productTradeDetail.setProfitRate(0.35);
		productTradeDetail.setRepaymentDate(Date.valueOf("2015-02-01"));
		productTradeDetail.setTerm("90");
		productTradeDetail.setValueDate(Date.valueOf("2015-01-01"));

		result.put("name", productTradeDetail.getName());
		result.put("invest_amount", productTradeDetail.getInvestAmount());
		result.put("term", productTradeDetail.getTerm());
		result.put("profit_rate", productTradeDetail.getProfitRate());
		result.put("value_date", productTradeDetail.getValueDate());
		result.put("repayment_date", productTradeDetail.getRepaymentDate());
		result.put("exchange_status", productTradeDetail.getExchangeStatus());

		return result;
	}

	/** 美丽理财认购记录查询
	 * 客户编号 uid  产品列表起始位置 start 分页显示行数 row
	 */
	@RequestMapping("my/meili")
	public Map<String, Object> meili(@RequestHeader(required = false) String uid, 
			Integer start, Integer row) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		if (start == null || start < 0) {
			start = 0;
		}

		if (row == null) {
			row = 20;
		}
		// 通过客户编号查询当前客户所有认购记录集合，并分页
		Invest invest = new Invest();
		invest.setStart(start);
		invest.setLimit(row);
		invest.setMemberId(uid);
		//美丽类型为1
		invest.setType(1);

		Page<Invest> page = investService.pageAll(invest);
		/*
		 * 订单ID oid 产品Icon地址 icon 产品编号 id 产品名称 name 购买金额 amount 购买日期
		 * purchase_date 交易状态 status 赚取收益 earned_profit
		 * 产品名称和交易状态 status，取Financing表的Invest status字段 
		 */
		List<Invest> investList = page.getContent();
		Map<String,Object> result = success();
		List<beautyFinanceSubscriptionInfo> products = new ArrayList<beautyFinanceSubscriptionInfo>();
		for (Invest invests : investList) {
			Financing financing =financingService.get(invests.getFinanceId());
			//产品名称
			String productName="";
			//投资状态 初始值为异常
			int status=-1;
			//产品地址
			String icon = "";
			if(financing!=null){
				productName = financing.getTitle();
				status=financing.getInvestStatus();
				icon = financing.getIcon();
			}else{
				continue;
			}			
			//投资状态
			//通过finacing表中的type=1 并且 invesst表中的status=0 为已返还，=1为未付款
			if(financing.getType().equals(Financing.TYPE_MEILI) && invests.getPaymentStatus() == 0){
				status=0;
			}else if (financing.getType().equals(Financing.TYPE_MEILI) && invests.getPaymentStatus()==1){
				status=1;
			}else{
				continue;
			}
			products.add(new beautyFinanceSubscriptionInfo(
					invests.getId(),icon,invests.getFinanceId(),productName,invests.getAmount(),invests.getCreateTime(),status,invests.getExpectedProfit(),invests.getEarnedProfit()));
		}
		result.put("items", products);

		return result;

	}

	/**美丽理财产品交易详情查询
	 * @param id
	 * @param oid
	 * @param uid
	 * 订单编号 oid 客户编号 uid
	 */
	@RequestMapping("my/meili/{oid}")
	public Map<String, Object> meiliDetail(@PathVariable String oid,
			@RequestHeader(required = false) String uid) {
		/*
		 * 产品名称 name 投资金额 amount 期限 term 购买日期 purchase_date 还本日期 repayment_date
		 * 使用期限 exipry_date 赚取收益 earned_profit 返回状态 status 订单编码 order_code
		 */
		//invest表
		Invest invest= investService.get(oid);
		//finacing表
		Financing financing =  financingService.get(invest.getFinanceId());
		FinancingAttribute financingAttribute =financingAttributeService.get(invest.getFinanceId());
		if (invest == null || financing == null ||financingAttribute==null) {
			return failure(ResultCode.RECORD_NOT_EXIST);
		}
		Map<String,Object> result = success();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		if (invest != null) {
		    //产品编号
		    result.put("id", invest.getFinanceId());
			// 投资金额 amount
			result.put("amount", invest.getAmount());
			// 期限 term
			result.put("term", invest.getTerm());
			// 购买日期			
			String yymmdd = dateFormat.format(invest.getCreateTime()).toString();
			result.put("purchase_date", yymmdd);
			// 返还状态
			result.put("status", invest.getPaymentStatus());
			// 赚取收益
			result.put("earned_profit", invest.getEarnedProfit());
			//将赚取收益
			result.put("expected_profit", invest.getExpectedProfit());
			// 还本日期 = 
			result.put("repayment_date",dateFormat.format(DateUtils.addMonths(invest.getInvestDate(), invest.getTerm())));
			// 产品名称 name
			result.put("name", financing.getTitle());
			// 过期日期
		result.put("exipry_date", financingAttribute.getTimeLimit());

		// 订单编码 order_code 原始订单号
		result.put("order_code", invest.getId());
		return result;
	}
	/**
	 * 小豆理财认购记录查询
	 * @param uid
	 * @param productModel
	 * @param start
	 * @param row
	 * @return result
	 */
	@RequestMapping("my/xiaodou")
	Map<String, Object> buyDetail(@RequestHeader(required = false) String uid,
			String productModel, Integer start, Integer row) {

//		uid = "1";
		
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}

		if (start == null || start < 0) {
			start = 0;
		}

		if (row == null) {
			row = 20;
		}

		//通过客户编号查询当前客户所有认购记录集合，并分页
		Invest invest = new Invest();
		invest.setStart(start);
		invest.setLimit(row);
		invest.setMemberId(uid);
		//小豆类型为2
		invest.setType(2);
		List<BuyRecord> buyRecord;
		buyRecord = new ArrayList<BuyRecord>();
		Page<Invest> page = investService.pageAll(invest);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		List<Invest> investList = page.getContent();

		for (Invest invests : investList) {
			Financing financing = financingService.get(invests.getFinanceId());
			String title = "";
			int investStatus = financing.getInvestStatus();
			if (financing != null) {
				title = financing.getTitle();
				/** invest.PaymentStatus=1未付款 
				 *  invest.PaymentStatus=0 &&	Financing.INVEST_STATUS_SALE = 0 已付款;
	                invest.PaymentStatus=0 &&	Financing.STATUS_FULL_SCALE = 1 购买成功;
					invest.PaymentStatus=0 &&	Financing.INVEST_STATUS_REPAYMENT = 2  还款成功;
					invest.PaymentStatus=0 &&	Financing.INVEST_STATUS_PAID = 3;&& 已还款*/
				//edit by David 2015/04/20 start
				if(invests.getPaymentStatus()==null || invests.getPaymentStatus().intValue()==1){
					investStatus=4;//未付款
				}else if(invests.getPaymentStatus().intValue()==0){
					if(financing.getInvestStatus().intValue()==0){
						investStatus=5;//已付款
					}
//					else if(financing.getInvestStatus().intValue()==1){
//						investStatus=1;//购买成功
//					}else if(financing.getInvestStatus().intValue()==2){
//						investStatus=2;//还款中
//					}else if(financing.getInvestStatus().intValue()==3){
//						investStatus=3;//已还款
//					}
				}	
				//edit by David 2015/04/20 end
			}
			buyRecord.add(new BuyRecord(invests.getId(),
					invests.getFinanceId(), title, invests.getAmount(), sdf.format(invests.getInvestDate()).toString(), String.valueOf(investStatus),
					invests.getEarnedProfit()));
		}

		Map<String,Object> result = success();
		result.put("items", buyRecord);

		return result;

	}
	/**小豆理财产品交易详情查询
	 * @param id
	 * @param oid
	 * @param uid
	 * 订单编号 oid 客户编号 uid
	 */
	@RequestMapping("my/xiaodou/{oid}")
	public Map<String, Object> xiaodouDetail(@PathVariable String oid,
			@RequestHeader(required = false) String uid) {
		
		if(StringUtils.isBlank(uid)){
            return failure(ResultCode.MISSING_UID_PARAM);
        }

        if(StringUtils.isBlank(oid)){
            return failure(ResultCode.MISSING_PARAMS);
        }
		
		try {
			//invest表
			Invest invest= investService.get(oid);
			//finacing表
			Financing financing =  financingService.get(invest.getFinanceId());
			//edit by David 2015/04/20 start
			int investStatus = financing.getInvestStatus();
			if (financing != null) {				
				if(invest.getPaymentStatus()==null || invest.getPaymentStatus().intValue()==1){
					investStatus=4;//未付款
				}else if(invest.getPaymentStatus().intValue()==0){
					if(financing.getInvestStatus().intValue()==0){
						investStatus=5;//已付款
					}
//					else if(financing.getInvestStatus().intValue()==1){
//						investStatus=1;//购买成功
//					}else if(financing.getInvestStatus().intValue()==2){
//						investStatus=2;//还款中
//					}else if(financing.getInvestStatus().intValue()==3){
//						investStatus=3;//已还款
//					}
			//edit by David 2015/04/20 end
				}				
			}
			//通过查到financing表的term查到financial_package的信息
			FinancialPackage financialPackage = financialPackageService.getRate(financing.getTerm());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Map<String,Object> result = success();
			// 产品名称 name
			result.put("name", financing.getTitle());
			// 投资金额 amount
			result.put("invest_amount", invest.getAmount());
			// 期限 term
			result.put("term", invest.getTerm());
			// 收益率 profit_rate
			result.put("profit_rate", financialPackage.getInterestRate());
			//购买日期
			result.put("purchase_date", sdf.format(invest.getCreateTime()));
			// 起息日 value_date
			result.put("value_date", financialPackage.getValueDate());
			// 还本日期 repayment_date
			result.put("repayment_date", financialPackage.getSettlementDate());
			// 兑换状态 exchange_status 参考列表			
			result.put("exchange_status", investStatus);
//			result.put("order_code", Calendar.DATE);
			return result;
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.XIAODOU_SUBSCRIPTION_RECORD_NOT_EXIST);
		}

		// 订单编码 order_code
	}

	/**
	 * 交易记录查询
	 * 客户编号 uid 产品列表起始位置 start 分页显示行数 row
	 */
	@RequestMapping("my")
	public Map<String, Object> get(@RequestHeader(required = false) String uid,
			Integer start, Integer row) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		// uid = "1";
		if (start == null || start < 0) {
			start = 0;
		}

		if (row == null) {
			row = 20;
		}


		// 获取account相关number
		Account account = accountService.getInfoBymemberId(uid);
        if(account==null){
        	return failure(ResultCode.RECORD_NOT_EXIST);
        	
        }
		NotesBook nobook = new NotesBook();
		nobook.setStart(start);
		nobook.setLimit(row);
		nobook.setAccount(account.getNumber());

		Page<NotesBook> page = notesBookService.page(nobook);

		List<NotesBook> noteBookList = page.getContent();

		List<Transaction> transactions = new ArrayList<Transaction>();

		transactions=getTransactions(noteBookList,transactions);

		Map<String,Object> result = success();

		result.put("items", transactions);

		return result;
	}

	
	
	/**
	 * 单独查询当前投资金额和累计收益（小豆理财认购记录查询用）
	 * @param uid
	 * @param type
	 * @return result
	 */
	@RequestMapping("cumulative")
	Map<String, Object> buyCumulative(@RequestHeader(required = false) String uid,Integer type) {

		
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		if (type == null) {
		     return failure(ResultCode.MISSING_PARAMS);
		}
		//通过客户编号查询当前客户所有认购记录累计投资金额和累计收益
		Double cumulativeAmount = investService.getCumulativeAmountBymemberId(uid,type);
		Double cumulativeProfit = investService.getCumulativeProfitBymemberId(uid,type);
		

		Map<String,Object> result = success();
		result.put("cumulative_amount", cumulativeAmount==null?0:cumulativeAmount);
		result.put("cumulative_profit", cumulativeProfit==null?0:cumulativeProfit);

		return result;

	}
	
	/**四舍五入，保留两位小数*/
    public  Double roundDouble(double val, int precision) {   
        Double ret = null;   
        try {   
            double factor = Math.pow(10, precision);   
            ret = Math.floor(val * factor + 0.5) / factor;   
        } catch (Exception e) {  
        	logger.error(e.toString());
            e.printStackTrace();   
        }   
  
        return ret;   
    } 
    
	/**方法提出，交易记录查询*/
	public List<Transaction> getTransactions(List<NotesBook> noteBookList,
			List<Transaction> transactions) {
		for (NotesBook noteBook : noteBookList) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String txnDate = sdf.format(noteBook.getTxnDate());
			String type = String.valueOf(noteBook.getType());
			String amount = String.valueOf(noteBook.getAmount());
			if ("0.0".equals(amount)) {
				continue;
			}
			switch (noteBook.getType().intValue()) {
			case 0:
				type = "充值";
				amount = "+" + amount;
				break;
			case 1:
				type = "提现";
				amount = "-" + amount;
				break;
			case 3:
				type = "投资";
				amount = "-" + amount;
				break;
			case 4:
				type = "投资收益";
				amount = "+" + amount;
				break;
			case 5:
				type = "还款";
				amount = "-" + amount;
				break;
			case 7:
				type = "手续费费用";
				amount = "-" + amount;
				break;
			case 8:
				type = "返现收益";
				amount = "+" + amount;
				break;
			case 9:
				type = "在线支付";
				amount = "-" + amount;
				break;
			default:
				break;
			}
			transactions.add(new Transaction(type,amount,txnDate,NotesBook.NORMAL.equals(noteBook.getStatus()) ? "01": "02"));
		}
		return transactions;	
	}
	
	

}
